package org.wedding.center.util;

import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.StrUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.wedding.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 七牛云工具类
 * @author sky
 */
@Component
public class QiniuUtils {

    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.bucketName}")
    private String bucketName;
    @Value("${qiniu.path}")
    private String url;

    public String upload(InputStream file, String fileName){
        try {
            String token = auth.uploadToken(bucketName);
//            fileName = "myImage/"+fileName;
            fileName = "test/"+fileName;
            Response res = uploadManager.put(file, fileName, token, null, null);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛云出错:" + res);
            }
            return url+"/"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public CommonResult delete(String fileName) {
        try {
            String key = "myimage/"+fileName;
            Response delete = bucketManager.delete(bucketName, key);
            if (!delete.isOK()) {
                return CommonResult.failed("删除七牛云出错:" + delete.getInfo());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除七牛云出错:" + e.getMessage());
        }
        return CommonResult.success("删除成功");
    }
}
